package com.lingyuan.oms.handler.extend;

import com.alibaba.fastjson.JSON;
import com.lingyuan.common.core.domain.vo.call.WmsConstant;
import com.lingyuan.common.core.domain.vo.cart.CartItemVo;
import com.lingyuan.common.core.exception.GlobalException;
import com.lingyuan.common.core.utils.StringUtils;
import com.lingyuan.oms.constant.CartConstant;
import com.lingyuan.oms.domain.param.CreateOrderParam;
import com.lingyuan.oms.handler.AbstractHandler;
import com.lingyuan.oms.handler.Handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName：CartItemStockHandler
 * @Author: LeiHao
 * @Date: 2024/10/7 19:54
 * @Description: 校验购买商品库存
 */
@Component("cartItemStockHandler")
public class CartItemStockHandler extends AbstractHandler {
    private static final Logger logger = LoggerFactory.getLogger(CartItemStockHandler.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    @Override
    public boolean handle(CreateOrderParam createOrderParam) {
        // 校验库存
        List<Long> skuIdList = Arrays.stream(createOrderParam.getSkuIds().split(","))
                 .map(Long::parseLong)
                .collect(Collectors.toList());
        BoundHashOperations<String, Object, Object> boundHashOps =
                stringRedisTemplate.boundHashOps(CartConstant.CART_REDIS_KEY + createOrderParam.getUserId());
        List<Object> values = boundHashOps.values();
        List<CartItemVo> cartItemVoList = values.stream()
                .map(obj -> JSON.parseObject(obj.toString(), CartItemVo.class))
                .filter(cartItemVo -> skuIdList.contains(cartItemVo.getProductId()))
                .collect(Collectors.toList());

        cartItemVoList.forEach(cartItem -> {
            // 获取redis库存列表
            Integer stock = Integer.valueOf(stringRedisTemplate.boundHashOps(WmsConstant.WARE_LOCK_KEY_VALUE)
                    .get(String.valueOf(cartItem.getProductId()))
                    .toString());
            if (cartItem.getPayNum() > stock) {
                throw new GlobalException("skuId:" + cartItem.getProductId() + "库存不足");
            }
        });

        return super.handle(createOrderParam);
    }
}
